package com.olympus.hermes.product.service;

import com.olympus.hermes.common.service.AbstractService;
import com.olympus.hermes.common.support.PageRequest;
import com.olympus.hermes.product.bean.dto.brand.CreateBrandDTO;
import com.olympus.hermes.product.bean.dto.brand.OutputBrandDTO;
import com.olympus.hermes.product.repo.BrandRepo;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Mickey
 * @since 2021/1/20
 */
@Service
@AllArgsConstructor
public class BrandService extends AbstractService {

    private final BrandRepo brandRepo;

    public void create(CreateBrandDTO createBrand) {
        creatorFor(brandRepo)
                .instance(createBrand::convertTo)
                .call();
    }

    public Page<OutputBrandDTO> listByCondition(PageRequest pageRequest, Map<String, String> condition) {
        return brandRepo.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (condition.containsKey("name")) {
                predicates.add(builder.like(root.get("name"), "%" + condition.get("name") + "%"));
            }
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest).map(brand -> new OutputBrandDTO().reverse().convert(brand));
    }

    public void delete(List<Long> ids) {
        ids.forEach(brandRepo::deleteById);
    }
}
